<template>
    <div class="dict-container" :style="{ width: isCollapsed ? '45px' : '450px' }">
      <el-card 
        style="margin: 15px 0 15px 15px; height: calc(100vh - 120px);"
        :class="{ 'collapsed': isCollapsed }"
      >
        <div class="btnGroup">
          <el-button 
            type="primary" 
            size="small" 
            :icon="Plus"
            @click="handleAdd"
          >
            添加
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            :icon="Edit"
            :disabled="!actNode"
            @click="handleEdit"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            :icon="Delete"
            @click="handleDelete"
            :disabled="checkRows.length === 0"
          >
            删除
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            :icon="ArrowUp"
            @click="changeCollapsed"
          >
            收起
          </el-button>
        </div>
        <el-divider style="margin: 10px 0 15px;" />
        <!-- <el-input 
          v-model="typeName" 
          placeholder="请输入字典名称搜索" 
          :suffix-icon="Search"
          @input="handleSearch"
        /> -->
  
        <transition name="slide">
            <div v-loading="loading" :style="{ marginTop: !treeData.length ? '100px' : '0' }">
              <a-tree
                ref="treeRef"
                v-if="treeData.length && refreshTree"
                :defaultExpandAll="defaultExpandAll"
                checkable
                :tree-data="treeData"
                @select="handleSelect"
                @check="handleCheck"
                fieldNames="{ title: 'name', key: 'id', children: 'children' }"
              >
                <template #title="{ name, id }">
                  <span>{{ name }} {{ id }}</span>
                </template>
              </a-tree>
              <div v-else class="no-data">暂无数据</div>
            </div>
        </transition>
      </el-card>
  
      <!-- 折叠按钮 -->
      <transition name="fade">
        <div 
          class="collapse-btn" 
          @click="toggleCollapse"
        >
          <el-button 
            link
            size="small" 
            style="background-color: '#00000000';"
            :icon="isCollapsed ? ArrowRight : ArrowLeft"
          />
        </div>
      </transition>

      <TypeForm ref="typeformRef" @refresh="getDictTreeFn" />
    </div>
  </template>
  
  <script setup>
  import TypeForm from './typeForm.vue'
  import DictAPI from '@/api/system/dict.api.ts'
  import { ref, onMounted } from 'vue'
  import { Plus, Edit, Delete, ArrowUp, ArrowRight, ArrowLeft, Search } from '@element-plus/icons-vue'
  import { useSettingsStore } from "@/store";
  import useToggle from "@/hooks/useToggle";
  import { ThemeMode } from "@/enums/settings/theme.enum";
  const [refreshTree, changeRefreshTree , ] = useToggle(true);
  const [loading, changeLoading, ] = useToggle(false);
  const settingsStore = useSettingsStore();

  const changeTheme = (val) => {
    const tree = document.querySelector('.ant-tree');
    if(val === ThemeMode.DARK) {
      tree.style.backgroundColor = '#ffffff00'
      tree.style.color = '#fff'
    } else {
      tree.style.backgroundColor = '#fff'
      tree.style.color = '#000'
    }
  }
  watch(() => settingsStore.theme, changeTheme)
  
  
  const emit = defineEmits(['getDictType'])

  onMounted(() => {
    getDictTreeFn()
  })

  const changeCollapsed = () => {
    changeRefreshTree()

    defaultExpandAll.value = !defaultExpandAll.value

    nextTick(() => {
      changeRefreshTree()
      nextTick(() => {
        changeTheme(settingsStore.theme)
      })
    })
  }


  const getTypeRow = (indexs) => {
    let i = 0
    let row = treeData.value[indexs[i++]]
    while(i < indexs.length && row.children && row.children.length) {
      row = row.children[indexs[i++]]
    }

    return row
  }
  const handleSelect = (e) => {
    if(!e.length) return
    const [_, ...indexs] = e[0].split('-')
    console.log(indexs);
    const row = getTypeRow(indexs)
    actNode.value = row
    emit('getDictType', { id: row.id, code: row.code })
  }

  const checkRows = ref([]) // 选中的行inf
  const handleCheck = (e) => {
    checkRows.value = e.map(item => {
      const [_, ...indexs] = item.split('-')
      return getTypeRow(indexs)
    })
    console.log(checkRows.value);
  }

  const actNode = ref(null)

  const treeData = ref([])
  const defaultExpandAll = ref(true)
  const getDictTreeFn = async () => {
    changeLoading(true)
    treeData.value = await DictAPI.getDictTree().finally(() => {
      changeLoading(false)
    })
    nextTick(() => {
      changeTheme(settingsStore.theme)
    })
  }

  const isCollapsed = ref(false)
  
  const toggleCollapse = () => {
    isCollapsed.value = !isCollapsed.value
  }
  
  const typeformRef = ref(null)
  const handleAdd = () => {
    typeformRef.value.handleOpen({ pid: null, id: null }, {}, treeData.value)
  }
  
  const handleEdit = () => {
    typeformRef.value.handleOpen({ pid: null, id: actNode.value.id }, actNode.value, treeData.value)
  }
  
  const handleDelete = () => {
    ElMessageBox.confirm(
      '是否确定删除选中项?',
      '温馨提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      DictAPI.delDistType({
        typeIds: checkRows.value.map(item => item.id)
      }).then(res => {
        getDictTreeFn()
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
    })
  }
  
  const typeName = ref('') // 搜索关键字
  const handleSearch = (value) => {
    console.log('搜索:', value)
    getDictTreeFn(value)
  }
  </script>
  
  <style scoped>
  .no-data{
    text-align: center;
  }

  /deep/ .ant-tree-treenode .ant-tree-node-selected{
    color: #409EFF;
  }
  
  /* 过渡动画 */
  .slide-enter-active,
  .slide-leave-active {
    transition: all 0.3s ease;
  }
  
  .slide-enter-from,
  .slide-leave-to {
    opacity: 0;
    transform: translateX(20px);
  }
  
  .fade-enter-active,
  .fade-leave-active {
    transition: all 0.5s ease;
  }
  
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
  
  .dict-container {
    position: relative;
    height: 100%;
  }
  
  /* 折叠按钮样式 */
  .collapse-btn {
    position: absolute;
    right: 0px;
    top: 45%;
    transform: translateY(-50%);
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  /* 收起状态 */
  .dict-container .el-card.collapsed {
    width: 40px;
    overflow: hidden;
  }
  
  .dict-container .el-card.collapsed .btnGroup {
    display: none;
  }
  
  .dict-container .el-card.collapsed .el-divider {
    display: none;
  }
  
  .dict-container .el-card.collapsed .el-input {
    display: none;
  }
  
  .dict-container .el-card.collapsed .el-tree {
    display: none;
  }
  
  /* 按钮组样式 */
  .btnGroup {
    display: flex;
    flex-wrap: wrap;
  }
  
  .btnGroup button {
    margin: 0;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  
  /* 树形组件滚动条样式 */
  .dict-container .el-tree {
    height: calc(100% - 110px);
    overflow-y: auto;
  }
  
  .dict-container .el-tree::-webkit-scrollbar {
    width: 6px;
  }
  
  .dict-container .el-tree::-webkit-scrollbar-track {
    background: #f1f1f1;
  }
  
  .dict-container .el-tree::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }
  
  .dict-container .el-tree::-webkit-scrollbar-thumb:hover {
    background: #555;
  }
  
  /* 搜索框样式 */
  .dict-container .el-input {
    width: 100%;
  }
  
  .dict-container .el-card.collapsed {
    padding: 0;
  }
  </style>
